/**
 * Notes: Admin用户关联控制器
 * Date: 2024-01-01 00:00:00
 */

const BaseController = require('./base_controller.js');
const AdminModel = require('../model/admin_model.js');

class AdminUserLinkController extends BaseController {

    /**
     * 检查用户是否有admin权限
     */
    async checkUserAdminPermission() {
        try {
            // 严格以服务端身份为准：默认使用云端获取的 openId 作为唯一用户标识
            const serverUserId = this._userId; // 云端认证的 openId
            const clientUserId = this.getParameter('userId'); // 客户端传入的 userId（可选）

            // 仅当客户端传入的 userId 与服务端 openId 完全一致时才认可，否则一律忽略客户端的 userId
            let userId = serverUserId;
            if (clientUserId && clientUserId === serverUserId) {
                console.log('客户端userId与openId一致，采用一致的userId:', clientUserId);
                userId = clientUserId;
            } else if (clientUserId && clientUserId !== serverUserId) {
                console.warn(`客户端传入的 userId(${clientUserId}) 与 openId(${serverUserId}) 不一致，已忽略客户端 userId`);
            } else {
                console.log('使用系统openId作为userId:', userId);
            }

            if (!userId) {
                return {
                    success: false,
                    message: '用户未登录'
                };
            }

            // 直接通过admin表的linkedUserId字段查询admin账号
            const admin = await AdminModel.getOne({
                linkedUserId: userId,
                ADMIN_STATUS: 1,
                isActive: true
            }, 'ADMIN_ID,ADMIN_NAME,ADMIN_TYPE,linkedStoreIds,permissions,role');

            if (!admin) {
                return {
                    success: false,
                    message: '用户未关联admin账号'
                };
            }

            // 查询用户信息（可选，用于返回用户昵称等）
            const UserModel = require('../model/user_model.js');
            const user = await UserModel.getOne({
                _id: userId
            }, '_id,nickName');

            return {
                success: true,
                data: {
                    hasPermission: true,
                    adminInfo: {
                        adminId: admin.ADMIN_ID,
                        adminName: admin.ADMIN_NAME,
                        adminType: admin.ADMIN_TYPE,
                        linkedStoreIds: admin.linkedStoreIds || [],
                        permissions: admin.permissions || {},
                        role: admin.role || 'admin'
                    },
                    userInfo: {
                        userId: userId,
                        nickName: user ? user.nickName : '未知用户',
                        adminId: admin.ADMIN_ID
                    },
                    message: '用户具有admin权限'
                }
            };

        } catch (error) {
            console.error('检查用户admin权限失败:', error);
            return {
                success: false,
                message: error.message || '检查权限失败'
            };
        }
    }

    /**
     * 关联用户到admin账号
     */
    async linkUserToAdmin() {
        try {
            // 数据校验
            let rules = {
                userId: 'required|string|name=用户ID',
                adminId: 'required|string|name=Admin ID',
                permissions: 'object|name=权限配置',
                linkedStoreIds: 'array|name=关联门店ID列表'
            };

            let input = this.validateData(rules);

            // 检查admin账号是否存在
            const admin = await AdminModel.getOne({
                ADMIN_ID: input.adminId,
                ADMIN_STATUS: 1
            });

            if (!admin) {
                return {
                    success: false,
                    message: 'Admin账号不存在或已禁用'
                };
            }

            // 更新admin账号关联信息
            const updateData = {
                linkedUserId: input.userId,
                linkedStoreIds: input.linkedStoreIds || [],
                permissions: input.permissions || {},
                ADMIN_EDIT_TIME: Date.now()
            };

            await AdminModel.edit({
                ADMIN_ID: input.adminId
            }, updateData);

            return {
                success: true,
                data: {
                    message: '用户关联成功',
                    adminId: input.adminId,
                    userId: input.userId
                }
            };

        } catch (error) {
            console.error('关联用户到admin失败:', error);
            return {
                success: false,
                message: error.message || '关联失败'
            };
        }
    }

    /**
     * 取消用户admin关联
     */
    async unlinkUserFromAdmin() {
        try {
            // 数据校验
            let rules = {
                userId: 'required|string|name=用户ID'
            };

            let input = this.validateData(rules);

            // 查找关联的admin账号
            const admin = await AdminModel.getOne({
                linkedUserId: input.userId
            });

            if (!admin) {
                return {
                    success: false,
                    message: '用户未关联admin账号'
                };
            }

            // 清除admin账号关联信息
            await AdminModel.edit({
                ADMIN_ID: admin.ADMIN_ID
            }, {
                linkedUserId: '',
                linkedStoreIds: [],
                permissions: {},
                ADMIN_EDIT_TIME: Date.now()
            });

            return {
                success: true,
                data: {
                    message: '用户关联已取消',
                    adminId: admin.ADMIN_ID,
                    userId: input.userId
                }
            };

        } catch (error) {
            console.error('取消用户admin关联失败:', error);
            return {
                success: false,
                message: error.message || '取消关联失败'
            };
        }
    }

    /**
     * 获取用户关联的admin列表
     */
    async getUserLinkedAdmins() {
        try {
            // 数据校验
            let rules = {
                userId: 'required|string|name=用户ID'
            };

            let input = this.validateData(rules);

            // 查询关联的admin账号
            const admin = await AdminModel.getOne({
                linkedUserId: input.userId,
                ADMIN_STATUS: 1,
                isActive: true
            }, 'ADMIN_ID,ADMIN_NAME,ADMIN_TYPE,linkedStoreIds,permissions,role,ADMIN_LOGIN_TIME');

            const admins = admin ? [admin] : [];

            // 查询用户信息（可选）
            const UserModel = require('../model/user_model.js');
            const user = await UserModel.getOne({
                _id: input.userId
            }, '_id,nickName');

            return {
                success: true,
                data: {
                    admins: admins,
                    count: admins.length,
                    userInfo: {
                        userId: input.userId,
                        nickName: user ? user.nickName : '未知用户'
                    }
                }
            };

        } catch (error) {
            console.error('获取用户关联admin列表失败:', error);
            return {
                success: false,
                message: error.message || '获取列表失败'
            };
        }
    }
}

module.exports = AdminUserLinkController;
